const mysql = require("mysql")

const connection = mysql.createConnection({
    user: 'root',
    password: '111111',
    database: 'cxldb',
    host: '127.0.0.1',
    port: 3306
})
const connectionConnect = () => {
    connection.connect((err) => {
        !err ? console.log("数据库连接成功") : console.log(err);
    })
}


const query = (sql) => {
    return new Promise((resolve, reject) => {
        connection.query(sql, (err, data) => {
            if (err) {
                reject(err)
            } else {
                resolve(data)
            }
        })
    })
}

const defaultTables = {
    sys_essay: `
    CREATE TABLE sys_essay (
        id int(10) NOT NULL AUTO_INCREMENT,
        title varchar(30) DEFAULT NULL,
        user varchar(30) DEFAULT NULL,
        createTime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        des varchar(30) DEFAULT NULL,
        PRIMARY KEY (id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    `,
    sys_user: `
    CREATE TABLE sys_user (
        id int(20) NOT NULL AUTO_INCREMENT,
        username varchar(30) NOT NULL,
        password varchar(50) DEFAULT '123456',
        email varchar(50) DEFAULT NULL,
        phone varchar(20) DEFAULT NULL,
        nickname varchar(50) DEFAULT NULL,
        address varchar(50) DEFAULT '未知',
        createTime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY username (username)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    `
}


const createTables = async (arr = ['sys_essay', 'sys_user']) => {
    arr.forEach(async item => {
        console.log("xxxxxxxxxxxxxxxxxxx", `Sdesc ${item}`);
        const res = await query(`SHOW TABLES LIKE '${item}'`)
        console.log(res);
        if (res.length === 0) {
            query(defaultTables[item])
        }
    })
}


module.exports = {
    connection: connectionConnect,
    query,
    createTables
}